﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Harkon.AppServer.cOne.Registry;
using log4net;

namespace Harkon.AppServer.cOne.Service
{
    public class AbstractService : IService
    {

        private const int INITIALIZED = 1;
        private const int STARTED = 2;
        private const int STOPPED = 0;

        private int state = 0;

        private static ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region IService Members

        public ServiceName Name { get; set; }

        public IRegistry ServiceRegistry { get; set; }

        #endregion

        #region ILifecycleAware Members

        public ServiceState CurrentServiceState
        {
            get
            {
                if (state == 0)
                {
                    return ServiceState.Stopped;
                }
                if ((state & STARTED) != 0)
                {
                    return ServiceState.Started;
                }
                return ServiceState.Initialized;
            }
        }

        public virtual bool Init()
        {
            if ( (state & INITIALIZED) != 0)
            {
                logger.WarnFormat("{0} already initialized", Name);
                return false;
            }
            logger.DebugFormat("{0} initialized", Name);
            state = INITIALIZED;
            return true;
        }

        public virtual bool Start()
        {
            if ((state & STARTED) != 0)
            {
                logger.WarnFormat("{0} already running", Name);
                return false;
            }
            logger.DebugFormat("{0} running", Name);
            state = STARTED;
            return true;
        }

        public virtual bool Stop()
        {
            logger.DebugFormat("{0} stopped", Name);
            state = STARTED;
            return true;
        }

        #endregion
    }
}
